import logging

from django.shortcuts import render

# Create your views here.
from fdfs_client.client import get_tracker_conf, Fdfs_client
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR, HTTP_404_NOT_FOUND
from rest_framework.viewsets import ModelViewSet, GenericViewSet, ReadOnlyModelViewSet

from config.fastdfsConfig import FASTDFS_SERVER_DOMAIN
from users.utils import Mypermission
from utils.permission import *
from .serializers import *

# tracker server的实例化
tracker_path = get_tracker_conf('utils/fastdfs/client.conf')
client = Fdfs_client(tracker_path)

# 导入日志器
logger = logging.getLogger(__name__)


class ClassificationViewSet(ModelViewSet):  # 后台操作的视图
    # 查询集只需要拿到顶层的分类
    queryset = Classification.objects.filter(is_delete=False, parent=None)
    serializer_class = ParentClassificationSerializer
    permission_classes = [Mypermission]


class ClassificationStudentViewSet(GenericViewSet, ListModelMixin):  # 用户操作的视图
    # 查询集只需要拿到顶层的分类
    queryset = Classification.objects.filter(is_delete=False, parent=None)
    serializer_class = ParentClassificationSerializer
    permission_classes = [IsAuthenticated]

    @action(methods=['get'], detail=True)
    def commodity(self, request, pk):  # 点击指定分类得到所属该标签下商品
        # 获取指定分类的所有商品
        try:
            classification = Classification.objects.filter(is_delete=False).get(id=pk)
        except Classification.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        # 判断分类是顶层还是子分类
        classification_attr = 'classification1'
        classification_name = classification.name
        if classification.parent:
            classification_attr = 'classification2'
            # data = classification.classification2.filter(is_delete=False)
            classification_name = f'{classification.parent.name}-{classification_name}'
        # else:
        # data = classification.classification1.filter(is_delete=False)
        data = getattr(classification, classification_attr).filter(is_delete=False)
        return Response({'classification': classification_name, 'commodity': CommoditySerializer(data, many=True).data})


class CommodityViewSet(ModelViewSet):  # 商品表增删改查
    queryset = Commodity.objects.filter(is_delete=False)
    serializer_class = CommoditySerializer
    permission_classes = [Mypermission]

    #  接下来思考商品图的上传路由的设计：/shopping/commodity/1/img
    @action(methods=['post'], detail=True)
    def img(self, request, pk):  # 这里图片是一张一张上传，上传一张调一次这个接口
        # 得到商品
        try:
            commodity = self.get_queryset().get(id=pk)
        except Commodity.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)
        # 获取文件数据 校验文件格式等
        files = request.FILES.get('file')  # 获取文件的方法
        # print(files,111111111111)
        if not files or files.content_type not in ('image/jpeg', 'image/png', 'image/gif'):
            return Response(status=HTTP_400_BAD_REQUEST)

        # 上传到FastDFS文件系统中
        try:
            image_ext_name = files.name.split('.')[-1]  # 获得文件后缀名
        except Exception as e:  # 如果文件后缀名有.,就设置默认后缀名
            image_ext_name = 'png'

        try:  # 上传到 storage
            upload_res = client.upload_by_buffer(files.read(), file_ext_name=image_ext_name)  # 通过文件字节上传,指定文件格式

        # 这里如果出了问题，就是server出错了，需要把问题存入日志器
        except Exception as e:  # 这里的日志器是django的
            logger.error('图片上传出现错误：{}'.format(e))
            return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            if upload_res.get('Status') != 'Upload successed.':
                return Response({'msg': '图片上传失败，请稍后重试或联系管理员'}, status=HTTP_500_INTERNAL_SERVER_ERROR)
            else:
                image_name = upload_res.get('Remote file_id').decode()
                image_url = FASTDFS_SERVER_DOMAIN + image_name

        CommodityImg.objects.create(src=image_url, commodity=commodity)
        return Response({'data': image_url})


class CommodityStudentViewSet(GenericViewSet, RetrieveModelMixin):
    queryset = Commodity.objects.filter(is_delete=False, status=1)
    serializer_class = CommoditySerializer
    permission_classes = [IsAuthenticated]

    @action(methods=['get'], detail=False)
    def optimization(self, request):  # 优选书籍功能，以评论数排序
        queryset = self.get_queryset().order_by('-comments').order_by('-create_time')
        if len(queryset) >= 5:
            queryset = queryset[:5]
        return Response(self.get_serializer(queryset, many=True).data)


class ShoppingCartViewSet(ModelViewSet):
    serializer_class = ShoppingCartSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.shoppingcart_set.all()

    @create_user_auto
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    @update_user_auto(ShoppingCart)
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)

    @destroy_user_auto(ShoppingCart)
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)


class OrderViewSet(ReadOnlyModelViewSet, CreateModelMixin):
    serializer_class = OrderSerializer
    permission_classes = [IsAuthenticated]

    # User.objects.get().order_set
    def get_queryset(self):
        return self.request.user.order_set
